<?php
/**
 * Created by PhpStorm.
 * Script Name: Mp.php
 * Create: 12/26/22 7:18 PM
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;

use app\common\constant\Common;
use app\common\service\Qrcode as QrcodeService;
use EasyOpen\Tencent\Client as TencentCli;
use EasyOpen\Tencent\Request\Mp\ComponentFastregisterweapp;
use plugin\wechat\app\model\MiniReg as MiniRegM;
use plugin\wechat\app\service\OpenPlatform as OpenPlatformService;
use plugin\wechat\app\TenantController;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\service\Common as CommonService;
use plugin\wechat\app\service\Mini as MiniService;
use plugin\wechat\app\service\MiniReg as RegService;
use Support\Request;
use plugin\wechat\app\service\Setting as SettingService;

class Minireg extends TenantController
{
    /**
     * @var MiniRegM
     */
    protected $model;
    /**
     * @var TencentCli
     */
    private TencentCli $client;

    public function __construct(){
        parent::__construct();
        $this->model = new MiniRegM();
        $this->client = new TencentCli();
        $this->insertTenantId = true;
    }

    private function tabList(){
        return [
            'mini' => ['title' => '已有账号', 'href' => url('mini/index')],
            'reg' => ['title' => '注册记录', 'href' => url('minireg/index')]
        ];
    }
    
    /**
     * 代注册
     * @param Request $request
     * @return mixed|\support\Response
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \Exception
     */
    public function add(Request $request){
        if(request()->isPost()){
            $post_data = input('post.');
            $res = $this->validate($post_data,'\\plugin\\wechat\\app\\validate\\MiniReg.add');
            if($res !== true){
                return $this->error($res, '', ['token' => token()]);
            }
            $res = OpenPlatformService::registerMiniprogram($post_data);
            if($res !== true) {
                return $this->error('微信返回错误：'.$res, '', ['token' => token()]);
            }
            $post_data['company_id'] = TenantService::getCompanyId();
            $post_data['tenant_id'] = $this->tenantInfo('id');
            RegService::reg($post_data);
            return $this->success('提交成功，请法人留意微信消息，继续完成认证！', '');
        }

        $builder = new FormBuilder();
        $builder->setTip('认真填写以下信息，即可快速完成小程序注册！')
            ->addFormItem('name', 'text', '企业名称', '需与工商部门登记信息一致', [], 'required')
            ->addFormItem('code', 'text', '企业代码', '填写企业代码', [], 'required')
            ->addFormItem('code_type', 'select', '企业代码类型', '企业代码类型', RegService::codeTypes(), 'required')
            ->addFormItem('legal_persona_wechat', 'text', '法人微信号', '填写法人微信号，注意不是昵称', [], 'required')
            ->addFormItem('legal_persona_name', 'text', '法人姓名', '注意和开户银行保持一致',[], 'required')
            ->addFormItem('component_phone', 'number', '第三方联系电话', '请填写手机号');
        return $builder->show();
    }

    public function index(){
        if(request()->isPost()){
            $post_data = input('post.');
            $where = [
                ['company_id', '=', TenantService::getCompanyId()],
                ['tenant_id', '=', $this->tenantInfo('id')]
            ];
            !empty($post_data['search_key']) && $where[] = ['name|code|legal_persona_name|legal_persona_wechat', 'like', '%'.$post_data['search_key'].'%'];

            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('update_time', 'desc')
                    ->select();
            } else {
                $list = [];
            }

            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '搜索词','placeholder' => '企业名称、企业代码、法人微信号或法人姓名']
        ])
            ->setTabNav($this->tabList(), 'reg')
            ->addTopButton('addnew', ['href' => url('add'), 'text' => '快速注册'])
            ->addTableColumn(['title' => '序号', 'type' => 'index', 'minWidth' => 70])
            ->addTableColumn(['title' => '企业名称', 'field' => 'name', 'minWidth' => 100])
            ->addTableColumn(['title' => '企业代码', 'field' => 'code', 'minWidth' => 100])
            ->addTableColumn(['title' => '法人姓名', 'field' => 'legal_persona_name', 'minWidth' => 100])
            ->addTableColumn(['title' => '法人微信', 'field' => 'legal_persona_wechat', 'minWidth' => 100])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'type' => 'enum', 'options' => RegService::status()])
            ->addTableColumn(['title' => '提交时间', 'field' => 'create_time',  'minWidth' => 180])
            ->addTableColumn(['title' => '操作', 'minWidth' => 150, 'type' => 'toolbar'])
            ->addRightButton('edit', ['href' => url('info', ['id' => '__data_id__']), 'text' => '查看进度'])
            ->addRightButton('self', ['href' => url('quickRegPost', ['id' => '__data_id__']), 'text' => '复用信息注册', 'data-ajax' => true, 'data-confirm' => true]);
        return $builder->show();
    }

    /**
     * 管理设置
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function info(){
        $id = input('id', 0);
        $where = [
            ['company_id', '=', TenantService::getCompanyId()],
            ['tenant_id', '=', $this->tenantInfo('id')]
        ];
        if(! $info = $this->model->where($where)->find($id)){
            return $this->error('数据不存在!');
        }
        $res = OpenPlatformService::registerMiniprogram($info, 'search');
        if($res !== true) {
            return $this->error('微信返回错误：'.$res);
        }
        return json($res);
        $assign = [];
        return $this->show($assign);
    }
    
    /**
     * 复用信息注册
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function quickRegPost(){
        $id = input('id', 0);
        $where = [
            ['company_id', '=', TenantService::getCompanyId()],
            ['tenant_id', '=', $this->tenantInfo('id')]
        ];
        if(! $info = $this->model->where($where)->find($id)){
            return $this->error('数据不存在!');
        }
        $info = $info->toArray();
        unset($info['id'], $info['create_time'], $info['update_time']);
        $res = OpenPlatformService::registerMiniprogram($info);
        if($res !== true) {
            return $this->error('微信返回错误：'.$res);
        }
        
        RegService::reg($info);
        return $this->success('提交成功，请法人留意微信消息，继续完成认证！');
    }
}